<?php
/**
 * @author Artur Bier <izatop@gmail.com>
 * @package Db.Query
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
/**
 * DbQueryAnalyzer
 */
class DbQueryAnalyzer extends Object 
{
	/**
	 * PDO object
	 *
	 * @var PDO
	 */
	private $handler;
	
	/**
	 * SQL String
	 *
	 * @var string
	 */
	private $sql;
	
	private $type;
	private $iscount;
	private $place;
	
	private static $lastSQL;
	
    /**
     * Конструктор класса
     * 
     * @param string $sql
     * @param PDO $handler
     */
    public function __construct($sql, mysqli $handler = null)
    {
    	$this->sql = $sql;
    	$this->handler = $handler;
    	self::$lastSQL = $sql;
    	
    	if(preg_match("/\s*(?<type>[a-z]+)\s+((?<iscount>COUNT([a-z0-9\*_-]+)?).+\/\*\s*(?<place>[a-z0-9_-]{1,10})\s*\*\/?)?/uis", $this->sql, $matches)) {
    		$this->type = mb_strtoupper($matches['type']);
    		$this->iscount = (isset($matches['iscount']) ? true : false);
    		$this->place = (isset($matches['place']) ? $matches['place'] : null);
    	}
    }
    
    public function isWrite()
    {
        switch ($this->type) {
            case 'INSERT':
            case 'UPDATE':
            case 'DELETE':
            case 'REPLACE':
                return true;
            default:
                return false;
        }
    }
    
    public function invoke($result)
    {
    	switch ($this->type) {
    		case 'SELECT':
    			return new DbResultSelect($result, $this->handler);
    		case 'INSERT':
    			return new DbResultInsert($result, $this->handler);
    		case 'UPDATE':
    			return new DbResultUpdate($result, $this->handler);
    		case 'REPLACE':
    			return new DbResultReplace($result, $this->handler);
    		case 'DELETE':
    			return new DbResultDelete($result, $this->handler);
			default:
				return $result;
    	}
    }
    
    public static function getLastSQL()
    {
        return self::$lastSQL;
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>